var router = require('koa-router')()
var db = require('../utils/mysql.js');
/* GET users listing. */
router.get('/reg', ctx=> {
  ctx.render('users/reg.html' ,{title:'用户注册'});
});
// router.get('/login', ctx=>{
//   ctx.render('users/login.html' ,{title:'用户登录'});
// });
router.get('/loginOut', ctx=>{
  ctx.cookies.set('user','',{maxAge:0});
  ctx.body={'err':0}
});
router.get('/info',async ctx=>{
  ctx.log('infolll')
  // var user = JSON.parse(ctx.cookies.get('user')||'{}');
  var user = JSON.parse(new Buffer(ctx.cookies.get('user'), 'base64').toString()||'{}');
  if(user && user.id){
    user = await queryUser({id:user.id});
    if(user.length){
      user = user[0];
    }
    else{
      user = {}
    }
  }
  else{
    user = {};
  }
  ctx.body=user;
});
router.post('/addUser',async ctx=>{
	// 新增用户
  var data = ctx.request.body;
  var userName = data.userName;
  if(!userName){
    ctx.body={'err':1,'msg':'用户名为空'};
    return ;
  }
  if(!data.password){
    ctx.body={'err':1,'msg':'密码为空'};
    return ;
  }
  const result = await queryUser({userName:userName});
  if(result.length>0){
    ctx.body={'err':1,'msg':'用户名已存在'};
    return ;
  }
  var sql = "insert into blog_user(user_name,password,show_name) values (:userName,:password,:showName)";
  await db.query(sql,{userName:userName,password:data.password,showName:data.showName});
  // ctx.flash('success','注册成功');
  ctx.body={'err':0};
});
router.post('/login', async ctx=>{
	// 新增用户
  var data = ctx.request.body;
  var userName = data.userName;
  if(!userName){
     ctx.body={'err':1,'msg':'用户名为空'};
     return ;
  }
  if(!data.password){
     ctx.body={'err':1,'msg':'密码为空'};
     return ;
  }
  const result = await queryUser({userName:userName,password:data.password});
  if(result.length===0){
    ctx.body={'err':1,'msg':'用户名或密码错误'};
    return ;
  }
  ctx.log(JSON.stringify(result[0]))
  ctx.cookies.set('user',  new Buffer(JSON.stringify(result[0])).toString('base64'));
  ctx.body={'err':0};
  ctx.log('end');
});

async function queryUser(user={}){
	var sql = "select id , user_name userName,password ,show_name showName from blog_user where 1";
	var queryObj = {};
	if(user.id){
		sql += " and id=:id";
		queryObj.id = user.id;
	}
	if(user.userName){
		sql += " and user_name=:userName";
		queryObj.userName = user.userName;
	}	
	if(user.password){
		sql += " and password=:password";
		queryObj.password = user.password;
	}
	if(user.showNameLike){
		sql += " and show_name like %:showNameLike%";
		queryObj.showNameLike = user.showNameLike;
	}
	return await db.query(sql,queryObj);
}

router.get('/my/:username', ctx=>{
  ctx.send('user: ' + ctx.params.username);
});

router.get('/', ctx=>{
  var user = JSON.parse(ctx.cookies.get('user')||'{}');
	if(user && user.id){
  	ctx.send('user: ' + util.inspect(user.showName));
		return;
	}
  ctx.send('respond with a resource');
});

module.exports = router;
